<?php
/* view_tweets.php */

session_start();

/* Destroy the session if the user is logging out */
if ((isset($_GET['logout'])) && ($_GET['logout']=='true')) {
    $_SESSION = array();
    session_unset();
    session_destroy();
    session_start();

    header('Location:view_tweets.php');
}

/* Include the config file */
require_once('db.php');
require_once('config.php');

/* include the twitter OAuth library files */
require_once('lib/twitterOAuth.php');
require_once('lib/OAuth.php');

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<head>
  <title>oo_tweet_tools</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8;" />
  <link rel="stylesheet" href="<?= $css_file; ?>" media="screen" />
</head>
<body>

<?php
$db = new XE_DB;

if ($db) {
    $exist_table = $db->mysql_is_table($table);
}

if ($exist_table) {
    $query = 'select * from '.$table.';';
    $db->execute_query($query);
    $total_tweets = $db->get_num_rows();
}

echo '<div id="header">';
    /*
    Create a new TwitterOAuth object, and then
    get a request token. The request token will be used
    to build the link the user will use to authorize the
    application. 

     You should probably use a try/catch here to handle errors gracefully
    */
if ((!isset($_SESSION['oauth_access_token'])) || ($_SESSION['oauth_access_token'])=='') {
    $to = new TwitterOAuth($consumer_key, $consumer_secret);
    $tok = $to->getRequestToken();

    $request_link = $to->getAuthorizeURL($tok);

    /*
    Save tokens for later  - we need these on the callback page to ask for the
    access tokens
    */
    $_SESSION['oauth_request_token'] = $token = $tok['oauth_token'];
    $_SESSION['oauth_request_token_secret'] = $tok['oauth_token_secret'];

    echo '<div class="gnb_login"><a href="'.$request_link.'">login using twitter</a></div>';
} else {
    $to = new TwitterOAuth($consumer_key, $consumer_secret, $_SESSION['oauth_access_token'], $_SESSION['oauth_access_token_secret']);
    $content = $to->OAuthRequest('https://twitter.com/account/verify_credentials.json', 'GET', array());
    $user = json_decode($content);
    
    $content = $to->OAuthRequest('https://twitter.com/account/rate_limit_status.json', 'GET', array());
    $limit = json_decode($content);

    if ($user->screen_name!='') {
        echo '<div class="gnb_login">'.$user->screen_name.' | ';
	echo '<a href="view_tweets.php?logout=true">Logout</a></div>';

	echo '<ul>';
	echo '<li><img src="'.$user->profile_image_url.'" /></li>';
	echo '<li>followng: '.$user->friends_count.'</li>';
	echo '<li>followers: '.$user->followers_count.'</li>';
	echo '<li>listed: '.$user->listed_count.'</li>';
	echo '<li>updates: '.$user->statuses_count.'</li>';
	echo '<li>started on '.date('Y.m.d',strtotime($user->created_at)).'</li>';

        echo '<li>limit: '.$limit->remaining_hits.' / '.$limit->hourly_limit.'</li>';
	echo '<li>reset time: '.date('H:i:s',strtotime($limit->reset_time)).'</li>';
	echo '<li><a href="view_dms.php">dm room</a></li>';
	echo '</ul>';
    } else {
        echo '<div class="gnb_login">Error: Unknown User | <a href="index.php?logout=true">Try Again</a></div>';
    }

    $content = $to->OAuthRequest('https://api.twitter.com/1/statuses/user_timeline.json?include_rts=t&count='.$cnt_tweets, 'GET', array());
    $status = json_decode($content);

    echo '<ol>';
    $i = 0;
    if ($exist_table)
    {
	foreach ($status as $tweet) {
	    $query = 'select * from '.$table.' where id="'.$tweet->id.'";';
	    $db->execute_query($query);
	    if ($db->get_num_rows() == 0) {
		$i++;
		echo '<li>'.$tweet->text.'</li>';
	    }
	}

    } else {
	foreach ($status as $tweet) {
	    echo '<li>'.$tweet->text.'</li>';
	}
    }
    echo '</ol>';

    if ($total_tweets == 0) {
	echo '<p><a href="save_all_tweets.php">you can start backup now</a></p>';
    } else if ($i) {
	echo '<p><a href="save_tweets.php">save tweets</a></p>';
    } else {
	echo '<p>nothing to save.</p>';
    }
}
echo '</div>';

if ($exist_table)
{
    echo '<div id="container"><h4>'.$total_tweets.' tweets has saved</h4>';
    echo '<ol>';
    $query = 'select * from '.$table.' order by id desc limit 0,50;';
    $db->execute_query($query);

    for ($i=1; $i<=$db->get_num_rows(); $i++) {
	$row = $db->next_row();
	$text = $row['text'];

	echo '<li>'.$text.'<br/>';
	echo '<a href="https://twitter.com/'.$user->screen_name.'/statuses/'.$row['id'].'">'.date('Y.m.d H:i:s',strtotime($row['created_at'])).'</a> via '.$row['source'].'</li>';
    }
    echo '</ol></div>';
} else {
    echo '<div id="container">';
    echo '<h1>Error: you have to install first.</h1>';
    echo '<div><a href="install.php">install</a></div>';
    echo '</div>';
}
    
$db->close();
?>

<?php
/* for Debug

foreach ($_SESSION as $key => $value) {
    echo $key.' = '.$value.'<br/>';
}
echo '<pre>';
print_r($user);
//print_r($user2);
print_r($limit);
print_r($status);
echo '</pre>';

*/
?>
<div id="footer">
<address>Powered by <a href='#'>oo_tweet for PHP</a></address>
</div>

</body>
</html>
